<?php
	include ('../defines.php');
	
	FunctionsHelper::includeFiles(
		array(
			ADMINISTRATOR_CONTROLLER_DIRECTORY . 'users.php',
			ADMINISTRATOR_CONTROLLER_DIRECTORY . 'news.php'
		)
	);

	$users = new Users();
	if (!$users->isLoggedUser())
		header('Location:' . ADMINISTRATOR_VIEW_PATH . 'login.php');

	$newsC = new NewsC();
	
	if (!empty($_POST)){
		$arrNews = array();
		$arrImages = array('type' => 'images');
		$arrAudios = array('type' => 'audios');
		$arrVideos = array('type' => 'videos');
		$arrTags = array('type' => 'tags');

		foreach ($_POST as $key => $value){
			if (strstr($key, 'image_text_')) $arrImages['texts'][$key] = $value;
			elseif (strstr($key, 'image_tag_')) $arrImages['tags'][$key] = $value;
			elseif (strstr($key, 'audio_text_')) $arrAudios['texts'][$key] = $value;
			elseif (strstr($key, 'audio_tag_')) $arrAudios['tags'][$key] = $value;
			elseif (strstr($key, 'video_text_')) $arrVideos['texts'][$key] = $value;
			elseif (strstr($key, 'video_link_')) $arrVideos['locations'][$key] = $value;
			elseif (strstr($key, 'video_tag_')) $arrVideos['tags'][$key] = $value;
			elseif (strstr($key, 'tag_text_')) $arrTags['texts'][$key] = $value;
			else $arrNews[$key] = $value;
		}
		
		
		foreach ($_FILES as $index => $value){
			if (strstr($index, 'image_filename_')) $arrImages['locations'][$index] = $value;
			elseif (strstr($index, 'audio_filename_')) $arrAudios['locations'][$index] = $value;
		}

		$arrNews['user_id'] = $users->getLoggedUser();

		if ($_POST['action'] != 'a') $operation = $newsC->updateNews($arrNews);
		else $operation = $newsC->createNews($arrNews);
		//operation is the new (or existing) news id.
		
		$newsC->InsertResource($operation, $arrImages);
		$newsC->InsertResource($operation, $arrAudios);
		$newsC->InsertResource($operation, $arrVideos);
		$newsC->InsertResource($operation, $arrTags);

		if ($operation)
			header('Location:' . ADMINISTRATOR_VIEW_PATH . 'news.php');
	}
	if (isset($_GET['id'])){
		$news = $newsC->getNews(
			array(
				'news_id' => $_GET['id']
			)
		);
	}else{
		$news = $newsC->getNews();
	}

	FunctionsHelper::includeTop();
?>
<div class="withBorder" id="main">

	<script type="text/javascript">
		$(function(){
			$('#back').click(function(){
				document.location.href='<?=ADMINISTRATOR_VIEW_PATH;?>news.php';
			});

			$('input[type=file]').live('change', function(){
				id = parseInt($(this).data('id'));
				if ($(this).hasClass('image')) classFile = 'image';
				else if ($(this).hasClass('audio')) classFile = 'audio';
				if (id == CountInputFiles(classFile))
					insertRowToAddResource($(this));
			});

			$('input[type=text].video, input[type=text].tag').live('keydown', function(){
				id = parseInt($(this).data('id'));
				if ($(this).hasClass('video'))
					classFile = 'video';
				else
					classFile = 'tag';
				if (id == CountInput(classFile))
					insertRowToAddResource($(this));
			});
			

			$('.deleteTag').click(function(){
				deleteResource('deleteTag', $(this), '<?=ADMINISTRATOR_CONTROLLER_PATH; ?>');
			});

			$('.deleteResource').click(function(){
				$main = $(this).closest('.resource');
				varUrl = '<?=ADMINISTRATOR_CONTROLLER_PATH; ?>operations.php';
				varData = { 'id' : $(this).attr('id'), 'resource-type': $main.data('resource-type'), 'controller' : 'news', 'operation' : 'deleteResource' };
				callAjax(varUrl, 'post', varData, funcSuccess);
			});
			
			
			$('.acceptResourceModification').click(function(){
				$main = $(this).closest('.resource');
				varUrl = '<?=ADMINISTRATOR_CONTROLLER_PATH; ?>operations.php';
				varData = { 'id' : $(this).attr('id'), 'resource-type': $main.data('resource-type'), 'controller' : 'news', 'operation' : 'modifyResource', 'text' : $main.find('.editResourceText').val(), 'tag' : $main.find('.editResourceTag').val() };
				callAjax(varUrl, 'post', varData, funcSuccess);
			});
						
						
			$('#frmNews').submit(function(){
				if ($('#text').length == 0)
					return false;
			});
		});
		
		var insertRowToAddResource = function($insertedRow){
			$main = $insertedRow.closest('.resourceInsertionMain');
			newId = parseInt($main.find('.row').length) + 1;
			
			$newRow = $($insertedRow.closest('.resourceInsertionMain').find('.row')[0]).clone();
			$($newRow.find('input[data-id]')[0]).attr('data-id', newId);
			$newRow.find('input').each(function(key, text){
				$(text).val('');
				$(text).attr('name', $(text).attr('name').substring(0, $(text).attr('name').lastIndexOf('_') + 1) + newId);
				$(text).attr('id', $(text).attr('id').substring(0, $(text).attr('id').lastIndexOf('_') + 1) + newId);
			});
			
			$main.append($newRow);
		};
	</script>
	<div class="mainABM bigMain" id="mainNews">
		<h1>ADMINISTRADOR DE NOTICIAS</h1>
		<form id='frmNews' class='form' method='POST' enctype="multipart/form-data">
			<input type='hidden' name='news_id' id='news_id' value='<?= $news->getNewsId(); ?>' />
			<input type='hidden' name='action' id='action' value='<?= $_GET['action']; ?>' />
			<div class="divContainerRequired">
				<div class="label noLeftPadding">T&iacute;tulo: </div><input type='text' value='<?= stripcslashes($news->getTitle()); ?>' class='required bigInput' name='title' id='subtitle' />
			</div>
			<br />
			<div class="label">Subt&iacute;tulo: </div><input type='text' value='<?= stripcslashes($news->getSubtitle()); ?>' class='bigInput' name='subtitle' id='subtitle' />
			<br />
			<div class="divContainerRequired">
				<div class="label noLeftPadding">Link: </div><input type='text' value='<?= $news->getLink(); ?>' class='bigInput url' name='link' id='link' />
			</div>
			<br />
			<div class="label">Fecha: </div><input type='text' value='<?= $news->getCreated(); ?>' class='required dateP tinyInput' name='created' id='created' />
			<br />
			<div class="label">Cuerpo: </div>
			<br />
			<br />
			<div class="containerMCE">
				<textarea class='required' name='text' id='text'><?= stripcslashes($news->getText()); ?></textarea>
			</div>
			<br />
			<hr />
			<br />
			<div class="label">Im&aacute;genes: </div>
			<br />
			
			<?
				function isOfType($resource, $type){
					return isset($resource[$type . '_id']);
				}
				
				function splitResourceData(&$resource){
					if (isOfType($resource, 'image')){
						$resource['id'] = $resource['image_id'];
						$resource['firstLetter'] = 'i';
						$resource['visible'] = MAIN_IMAGES_NEWS_PATH . $resource['name_file'];
					} elseif (isOfType($resource, 'audio')){
						$resource['id'] = $resource['audio_id'];
						$resource['firstLetter'] = 'a';
						$resource['visible'] = MAIN_FILES_DIRECTORY . $resource['name_file'];
					}elseif (isOfType($resource, 'video')){
						$resource['id'] = $resource['video_id'];
						$resource['firstLetter'] = 'v';
						$resource['visible'] = $resource['link'];
					}elseif (isOfType($resource, 'tag')){
						$resource['id'] = $resource['tag_id'];
						$resource['firstLetter'] = 't';
						$resource['visible'] = $resource['tag'];
						unset($resource['tag']);
					}
				}
			
				function renderResource($resourcesList){
					foreach ($resourcesList as &$resource){
						splitResourceData($resource);
			?>
						<div class="resource <?= isOfType($resource, 'image') ? 'currentSingleImage' : '';?>" data-resource-type="<?= $resource['firstLetter']; ?>">
							<?
								echo isOfType($resource, 'tag') ? '<li>' : '';
								if (isOfType($resource, 'image')){ ?>
								<img src="<?= $resource['visible']; ?>" alt=<?= $resource['name_file']; ?> /><br />
							<? 
								}else{
							?>
								<span class="resourceName"><?= $resource['visible']; ?></span>
							<? 
								} 
							?>

							<? $text_title = isOfType($resource, 'image') ? 'Ep&iacute;grafe' : 'Descripci&oacute;n';?>
							<? if (array_key_exists('text', $resource)){ ?><input type="text" class="editResourceText" placeholder="<?=$text_title;?>" value="<?= $resource['text']; ?>" title="<?=$text_title;?>" /><? } ?>
							<? if (array_key_exists('tag', $resource)){ ?><input type="text" class="editResourceTag" placeholder="Tag" value="<?= $resource['tag']; ?>" title="Tag" /><? } ?>
							<div class="<?= !isOfType($resource, 'image') ? 'same-line' : '';?>">
								<? if (!isOfType($resource, 'tag')){ ?>
								<a href="#" class="acceptResourceModification" id="<?= $resource['id']; ?>">Aceptar</a> 
								<? } ?>
								<span> - </span>
								<a href="javascript:void(0);" class="deleteResource" id="<?= $resource['id']; ?>">Eliminar</a>
							</div>
							<? echo isOfType($resource, 'tag') ? '</li>' : ''; ?>
						</div>
			<?			
					}
				}
			?>
			
			<div id="images">
				<p>Nota: Si borra una imagen o modifica su ep&iacute;grafe se recargar&aacute; el sitio por lo que se perder&aacute;n todos los cambios que no haya guardado.</p>
				<br />
				<div id="currentImages">
					<? renderResource($news->getImages()); ?>
				</div>
				
				<div class="resourceInsertionMain">
					<div class="row">
						<input type="file" name="image_filename_1" id="image_filename_1" class="image" data-id="1" />
						<input type="text" name="image_text_1" id="image_text_1" class="tinyInput resource-text" placeholder="Ep&iacute;grafe" title="Ep&iacute;grafe" />
						<input type="text" name="image_tag_1" id="image_tag_1" placeholder="Tag" class="miniTinyInput resource-tag" title="Tag" />
						<div class="clear"></div>
					</div>
				</div>
			</div>
			
			<br />
			<hr />
			
			<div id="audio">
				<div id="currentAudio">
					<div class="label">Audios:</div>
					<br />
					<? renderResource($news->getAudio()); ?>
				</div>
				
			
				<div class="resourceInsertionMain">
					<div class="row">
						<input type="file" name="audio_filename_1" id="audio_filename_1" class="audio" data-id="1" />
						<input type="text" name="audio_text_1" id="audio_text_1" class="tinyInput resource-text" placeholder="Descripci&oacute;n" title="Descripci&oacute;n" />
						<input type="text" name="audio_tag_1" id="audio_tag_1" placeholder="Tag" class="miniTinyInput resource-tag" title="Tag" />
						<div class="clear"></div>
					</div>
				</div>
			</div>
			
			<div class="clear"></div>
			<hr />
			<br />
			<div id="video">
				<div class="label">Videos:</div><br />
				<div id="currentVideo">
					<? renderResource($news->getVideo()); ?>				
				</div>
				<div class="resourceInsertionMain">
					<div class="row">
						<input type="text" name="video_link_1" id="video_link_1" class="video tinyInput" data-id="1" />
						<input type="text" name="video_text_1" id="video_text_1" class="tinyInput resource-text" placeholder="Descripci&oacute;n" title="Descripci&oacute;n" />
						<input type="text" name="video_tag_1" id="video_tag_1" placeholder="Tag" class="miniTinyInput resource-tag" title="Tag" />
						<div class="clear"></div>
					</div>
				</div>
			</div>
			
			<div class="clear"></div>
			<br />
			<hr />
			
			<div id="tags">
				<div class="label">Tags:</div><br />
				<div class="resourceInsertionMain">
					<div class="row">
						<input type="text" name="tag_text_1" id="tag_text_1" class="tag tinyInput" data-id="1" />
					</div>
				</div>
			</div>
			<div id="currentTag">
				<ul>
				<? renderResource($news->getTag()); ?>			
				</ul>
			</div>
			
			
			<div class="clear"></div>
			<p>Si no tilda la siguiente opci&oacute;n se cargar&aacute; lo rellenado en este formulario como una entrevista. Si la tilda, la misma ser&aacute; guardada como una noticia.</p>
			<input type="checkbox" name='is_news' id='is_news' value='1' <? echo $news->getIsNews() == 1 ? 'checked = "checked"' : ''; ?> /><label for="is_news">Es Noticia (o entrevista)</label>
			<br />
			<input type="checkbox" name='active' id='active' value='1' <? echo $news->isActive() == 1 ? 'checked = "checked"' : ''; ?> /><label for="active">Activo</label>
			<br />
			<div id="button"><input type="submit" name='sbmSubmit' id='sbmSubmit' value='Aceptar' /></div>
		</form>
		<img class="back" src='<?= ADMINISTRATOR_IMAGE_PATH . 'back.png'; ?>' id="back" width = '64' height = '52' />
	</div>
</div>

<?php
	
	FunctionsHelper::includeBottom();
?>